<meta charset="UTF-8">
<div id="importowner">
    <input type="file" id="file" style="display: none;" />
    <div class="full" style="padding: 10px;">
        <h3 class="h3-title">{{$t('bgMgr.importOwnerInfo')}}</h3>
        <div style="padding: 10px 0;">
            <i-table border ref="table" :columns="columns" :data="tableData" :loading="loading" :height="taleHeight"></i-table>
        </div>
        <div style="padding: 5px; text-align: center;border: 1px solid #DCDEE2;">
            <i-button @click="importTownerInfo">{{$t('insure.importFile')}}</i-button>
            <i-button @click="handleSubmit" :loading="loading" style="margin: 0 10px;">{{$t('header.submit')}}</i-button>
            <i-button @click="downloadTemplate">{{$t('insure.templateDownload')}}</i-button>
        </div>
    </div>
    <script>
        vueInstanse = new Vue({
            el: "#importowner",
            i18n: utils.getI18n(),
            data: {
                taleHeight: 300,
                loading: false,
                columns: [{
                    type: 'index',
                    width: 60
                }, {
                    title: vRoot.$t('alarm.devNum'),
                    key: "deviceid",
                    width: 140,
                }, {
                    title: vRoot.$t('insure.ownerName'),
                    key: "ownername"
                }, {
                    title: vRoot.$t('reportForm.address'),
                    key: "address"
                }, {
                    title: vRoot.$t('device.contact1'),
                    key: "phonenum1",
                    width: 120,
                }, {
                    title: vRoot.$t('device.contact2'),
                    key: "phonenum2",
                    width: 120,
                }, {
                    title: vRoot.$t('reportForm.idNumber'),
                    key: "idnum",
                    width: 160,
                }, {
                    title: vRoot.$t('device.gender'),
                    key: "gender",
                    width: 80,
                }, {
                    title: vRoot.$t('monitor.remarks'),
                    key: "remark",
                }, {
                    'title': vRoot.$t('insure.addStatus'),
                    width: 120,
                    render: function(h, params) {
                        var status = params.row.status;
                        var statusStr = '';
                        var color = '';
                        switch (status) {
                            case -1:
                                statusStr = vRoot.$t('insure.notSubmitted');
                                color = '#000';
                                break;
                            case 0:
                                statusStr = params.row.cause;
                                color = '#e4393c';
                                break;
                            case 1:
                                statusStr = vRoot.$t('insure.submitSucc');
                                color = '#007ACC';
                                break;
                        }
                        return h('span', {
                            style: {
                                color: color
                            }
                        }, statusStr)
                    },
                }, {
                    'title': vRoot.$t('alarm.action'),
                    width: 85,
                    render: function(h, params) {
                        return h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: function() {
                                    vueInstanse.tableData.splice(params.index, 1);
                                }
                            }
                        }, vRoot.$t('insure.remove'))
                    }
                }],

                tableData: [

                ],
                excelX: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
            },
            methods: {
                calcTableHeight: function() {
                    var wHeight = window.innerHeight;
                    this.taleHeight = wHeight - 170;
                },
                downloadTemplate: function() {
                    var a = document.createElement('a');
                    a.href = myUrls.apihost + (isZh ? 'ownertemplate.xlsx' : 'ownertemplateen.xlsx');
                    a.download = 'ownertemplate.xlsx';
                    a.click();
                },
                handleSubmit: function() {
                    if (this.tableData.length == 0) {
                        this.$Message.error(vRoot.$t('insure.importOwnerNameTips'));
                        return;
                    }
                    this.loading = true;
                    var tableData = deepClone(this.tableData),
                        me = this;

                    var owners = [];
                    tableData.forEach(function(item) {
                        if (String(item.deviceid).trim() != "") {
                            owners.push(item);
                        }
                    })

                    owners.forEach(function(item) {
                        if (item.gender.indexOf(vRoot.$t('device.man')) != -1) {
                            item.gender = 1
                        } else if (item.gender.indexOf(vRoot.$t('device.girl')) != -1) {
                            item.gender = 0
                        } else {
                            item.gender = -1
                        }
                    });
                    var url = myUrls.importOwnerInfo();
                    var data = {
                        owners: owners,
                        isforcecover: true,
                    }
                    utils.sendAjax(url, data, function(respData) {
                        me.loading = false;
                        if (respData.status == 0) {
                            if (respData.total === respData.success) {
                                me.$Message.success(vRoot.$t('insure.importSucceeded'));
                                me.tableData.forEach(function(item) {
                                    if (String(failItem.deviceid).trim() == String(item.deviceid).trim()) {
                                        item.status = 1;
                                    }
                                });
                            } else {
                                me.$Message.error(vRoot.$t('insure.total') + ":" + respData.total + "," + vRoot.$t('insure.fail') + ":" + respData.fail);
                                var errorrecords = respData.errorrecords;
                                var tableData = deepClone(me.tableData);
                                errorrecords.forEach(function(failItem) {
                                    tableData.forEach(function(item) {
                                        if (String(failItem.deviceid).trim() == String(item.deviceid).trim()) {
                                            item.status = 0;
                                            item.cause = failItem.cause;
                                        }
                                    });
                                })
                                tableData.forEach(function(item) {
                                    if (String(item.deviceid).trim() != "" && item.status == -1) {
                                        item.status = 1;
                                    }
                                });
                                me.tableData = tableData;
                            }
                        } else {
                            me.$Message.error(vRoot.$t('insure.importFailed'));
                        }
                    }, function() {
                        me.loading = false;
                        me.$Message.error(vRoot.$t('insure.importTimeout'));
                    });
                },
                importTownerInfo: function() {
                    this.fileEl.files.length = 0;
                    this.fileEl.value = "";
                    this.fileEl.click();
                },
                readWorkbookFromLocalFile: function(file, callback) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var data = e.target.result;
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        if (callback) callback(workbook);
                    };
                    reader.readAsBinaryString(file);
                },
                parserExcelData: function(excelData) {

                    try {
                        var indexY = 2;
                        var tableData = [];
                        while (true) {
                            var deviceIdKey = this.excelX[1] + indexY; //设备ID
                            var ownerNameKey = this.excelX[2] + indexY; //车主姓名
                            var genderKey = this.excelX[3] + indexY; // 性别
                            var idnumKey = this.excelX[4] + indexY; //身份证号
                            var phonenum1Key = this.excelX[5] + indexY; //联系号码1
                            var phonenum2Key = this.excelX[6] + indexY; //联系号码2
                            var addressKey = this.excelX[7] + indexY; //地址
                            var remarkKey = this.excelX[8] + indexY; //备注

                            if (excelData[deviceIdKey] == undefined && excelData[ownerNameKey] == undefined) {
                                break;
                            }

                            tableData.push({
                                deviceid: excelData[deviceIdKey] ? excelData[deviceIdKey].v : '',
                                ownername: excelData[ownerNameKey] ? excelData[ownerNameKey].v : '',
                                gender: excelData[genderKey] ? excelData[genderKey].v : '',
                                idnum: excelData[idnumKey] ? excelData[idnumKey].v : '',
                                phonenum1: excelData[phonenum1Key] ? excelData[phonenum1Key].v : '',
                                phonenum2: excelData[phonenum2Key] ? excelData[phonenum2Key].v : '',
                                address: excelData[addressKey] ? excelData[addressKey].v : '',
                                remark: excelData[remarkKey] ? excelData[remarkKey].v : '',
                                status: -1
                            })

                            indexY++;
                        }
                        this.tableData = tableData;
                    } catch (error) {
                        this.$Message.error(vRoot.$t('insure.importExcelFailTips'));
                    }


                }
            },
            mounted: function() {
                var me = this;
                this.fileEl = document.getElementById('file');
                this.fileEl.onchange = function(e) {
                    var idx = e.srcElement.value.lastIndexOf('.');
                    var houzhui = e.srcElement.value.slice(idx);
                    if (houzhui.indexOf('xlsx') == -1) {
                        me.$Message.error(vRoot.$t('insure.importExcelTips'));
                        return;
                    }
                    var file = e.target.files[0]
                    me.readWorkbookFromLocalFile(file, function(workbook) {
                        me.parserExcelData(workbook.Sheets['车主信息'])
                    });
                };
                this.calcTableHeight();
                window.onresize = function() {
                    me.calcTableHeight();
                }
            },
        })
    </script>
</div>